package capricornus.components.flower
{
	import capricornus.core.StageManager;
	import capricornus.res.DefaultResManager;
	import capricornus.utils.PointUtils;
	
	import com.greensock.TweenLite;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;

	internal class Flower
	{
		private static var _dict:Dictionary = new Dictionary();
		
		private var _index:int;
		private var _xSpeed:Number;
		private var _ySpeed:Number;
		private var _speed:Number;
		
		private var _bitmap:Bitmap;
		
		private var _isListen:Boolean = false;
		
		public function Flower( index:int, speed:Number )
		{
			_index = index;
			_speed = Math.random() * 0.2 + 0.05;
			init();
		}
		
		private function init():void
		{
			_dict[this] = this;
			
			var bd:BitmapData = DefaultResManager.instance.getDefaultFlower( _index );
			if( bd != null )
			{
				_bitmap = new Bitmap(bd);
			}
		}
		
		public function destroy():void
		{
			if( _bitmap.parent != null )
			{
				_bitmap.parent.removeChild( _bitmap );
			}
			_bitmap.bitmapData = null;
			if( _isListen )
			{
				_isListen = false;
				FlowerRefreshController.instance.removeEventListener( FlowerRefreshEvent.REFRESH, onRefresh );
			}
			delete _dict[this];
		}
		
		public function get bitmap():Bitmap
		{
			return _bitmap;
		}
		
		public function setLocation( x:int, y:int ):void
		{
			_fx = x;
			_fy = y;
			_bitmap.x = x;
			_bitmap.y = y;
		}
		
		public function fastFlyTo( x:int, y:int ):void
		{
			TweenLite.to( _bitmap, 1.5, {x:x, y:y, onComplete:onEnd} );
		}
		
		public function onEnd():void
		{
			flyTo( _bitmap.x, StageManager.stageHeight );
		}
		
		public function flyTo( x:int, y:int ):void
		{
			var f:Number = PointUtils.getPointToPointRadian( new Point(_bitmap.x, _bitmap.y), new Point(x,y) );
			var cos:Number = Math.cos( f );
			var sin:Number = Math.sin( f );
			
			_fx = _bitmap.x;
			_fy = _bitmap.y;
			_t = getTimer();
			_xSpeed = _speed * cos;
			_ySpeed = _speed * sin;
			
			_isListen = true;
			FlowerRefreshController.instance.addEventListener( FlowerRefreshEvent.REFRESH, onRefresh, false, 0, true );
		}
		
		private var _t:uint;
		private var _fx:Number;
		private var _fy:Number;
		private function onRefresh( e:FlowerRefreshEvent ):void
		{
			var t:uint = getTimer() - _t;
			_bitmap.x = int(_fx + _xSpeed * t);
			_bitmap.y = int(_fy + _ySpeed * t);
			if( _bitmap.x > StageManager.stageWidth || _bitmap.y > StageManager.stageHeight )
			{
				destroy();
			}
		}
	}
}






